<%--
  Created by IntelliJ IDEA.
  User: lt
  Date: 2018/8/31
  Time: 11:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<jsp:useBean id="today" class="java.util.GregorianCalendar" />
<html>
<head>
    <title>紧缺烟审批</title>

    <%--<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css">--%>
    <%--<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">--%>
    <%--<link rel="stylesheet" href="${contextPath}/static/layer/css/layui.css">--%>
    <script src="${contextPath}/static/statistics/js/jquery.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
    <script src="${contextPath}/static/statistics/js/vue.js"></script>
    <script src="${contextPath}/static/statistics/js/echarts.min.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>

    <link rel="stylesheet" href="${contextPath}/static/XiaLaDuoXuan/css/public.css" media="all" />
    <!-- 数型插件 -->
    <link href="${contextPath}/static/ztree/css/zTreeStyle.css" rel="stylesheet" />
    <script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js"></script>
    <script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>
    <!-- 年周 -->
    <script src="${contextPath}/static/time/datetime.js"></script>
    <%--<jsp:include page="../../head.jsp"/>--%>
    <style>
        .autocomplete-suggestions {
            border: 1px solid #999;
            background: #FFF;
            overflow: auto;
        }

        .autocomplete-suggestion {
            padding: 2px 5px;
            white-space: nowrap;
            overflow: hidden;
        }

        .autocomplete-selected {
            background: #F0F0F0;
        }

        .autocomplete-suggestions strong {
            font-weight: normal;
            color: #3399FF;
        }

        .layui-input{
            height: 30px;
        }
        .multiSelect{
            margin-top: -33px;
        }
        input{
            border:0;
            outline:0;
            border-style:none none solid none; /*  上 右 下  左 */
            background-color:transparent;
        }

        .ui-pg-div{
            display: none;
        }
    </style>
</head>
<body style="background: rgba(119, 118, 118, 0.15);">
<div class="container-fluid" id="app">
    <form class="form-inline layui-form" style="margin-top: 50px; margin-bottom: 5px;">
        <div class="form-group">
        <%--<label style="margin-left: 10px;">选择区域：</label>--%>
            <input id="zoneCode" class="form-control input-sm" type="text" placeholder="区域id" style="display: none">
            <input id="zoneName" onfocus="this.value=''" class="input-sm" type="text" placeholder="选择区域" style="width: 100px;" onclick="zoneHs()" readonly>
        </div>
        <div class="form-group">
            <input type="text" class="form-control input-sm" id="turnCreateDate" placeholder="查询开始时间">
        </div>
        <div class="form-group">
            <input type="text" class="form-control input-sm" id="bindCreateDate" placeholder="查询结束时间">
        </div>
        <button type="button" class="btn btn-white btn-info btn-sm customBtn" onclick="getXYShopTobacco();">
            <i class="ace-icon fa fa-search orange"> 查询</i>
        </button>
        <button type="button" class="btn btn-white btn-info btn-sm customBtn" id="" onclick="tablesToExcel()">
            <i class="ace-icon fa fa-key red"> 导出</i>
        </button>
        <%--<button type="button" class="btn btn-success" onclick="doPrint();" style="margin-top: 0px;">打印</button>--%>
        <button type="button" class="btn btn-white btn-info btn-sm customBtn" onclick="javascript:window.history.go(-1);window.close();">
            <i class="ace-icon fa fa-reply blue"> 返回</i>
        </button>
    </form>
    <div style="width: 100%; margin-bottom: 10px;">
        年份 :
        <select class="input-sm" id="yearId" onchange="getWeeks(this)" >
            <%--<option value="">请选择年份</option>--%>
            <c:forEach begin="${today.get(1)}" end="2020" var="i" step="1">
                <option value="<c:out value='${i}'/>"><c:out value='${i}'/>年</option>
            </c:forEach>
        </select>
        周次：
        <select class="input-sm" id="dateSearch" onchange="dateRange(this)">
            <option value="">请选择周次</option>
            <option v-for="(obj, index) in allwkObj" :selected="obj.selected" :value="obj.allwk">第{{obj.allwk}}周</option>
            <%--<c:forEach begin="${today.get(3)}" end="52" var="i" step="1">--%>
                <%--<option value="<c:out value='${i}'/>">第<c:out value='${i}'/>周</option>--%>
            <%--</c:forEach>--%>
        </select>
        时间段：<input id ="_dateRange_import" readonly="readonly" type="text" style="width: 180px;"/>
        <div style="float: right; color: red;">{{year}}</div>
    </div>

    <div class="row" style="background-color: rgb(53, 147, 202);margin-right: 0px;margin-left: 0px; height: 37px;">
        <div class="col-sm-10" style="margin-top: 6px;">
            <strong style="font-size: 18px;color: #f9f9f9;">紧缺烟审批</strong>
        </div>
        <div class="col-sm-2" style="text-align: right">

        </div>
    </div>
    <div class="table-responsive" id="tableContainer" style="height: 450px">
        <!--startprint-->
        <table class="table table-striped table-condensed table-bordered" id="sellwell" style="width: 1300px;">
            <tr style="background-color:#eee;">
                <th>商品\店铺</th>
                <th v-for="(shop, index) in shopList">{{ shop.shortName }}</th>
            </tr>
            <tr v-for="(obj, index) in shopProductList">
                <td v-for="(map, index) in obj" style="width: 100px;">
                    <div v-if="index == 0" style="width: 120px;">{{map.confirmQuantity}}</div>
                    <input type="text" class="input" v-else :value="map.confirmQuantity" :id="map.productCode" :name="map.shopId" :title="map.productName" ondblclick="singleKtTobaccoOrder(this.id,this.name,this.value,this.title)" style="border:0;outline:0;background-color:transparent;border-style:none none solid none; text-align: right;">
                </td>
            </tr>
            </tbody>
        </table>
        <!--endprint-->
    </div>


    <!-- 内容数据开始 -->
    <div class="col-xs-12">
        <table id="grid-table"></table>

        <div id="grid-pager"></div>

    </div>

    <div style="text-align: right;margin-top: 10px;" id="pageDiv"></div>
</div>
<!-- 新增商品内容 -->
<div id="authorizationInfoContent" class="hide">
    <div class="content_wrap" id="treeDemoProd">
        <div class="zTreeDemoBackgroundProd left">
            <div class="modal-body">
                <form id="confirmQuantityForm">
                    <div class="row">
                        <input type="text" name="productCode" id="productCode" style="display: none"/>
                        <input type="text" name="productName" id="productName" style="display: none"/>
                        <input type="text" name="shopId" id="shopId" style="display:none"/>
                        <input type="text" name="confirmQuantity" id="confirmQuantity" style="height: 35px;"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div>
        <button id="roleAuthorizationBtn" class="btn btn-success btn-sm" style="left: 182px;top: 58px;position: fixed;" onclick="saveSingleKtTobaccoOrder()">确认</button>
    </div>
</div>

<!-- 区域数型内容 -->
<div id="authorizationInfoContentZone" class="hide">
    <div class="content_wrap">
        <div class="zTreeDemoBackground left">
            <ul id="zoneDemo" class="ztree"></ul>
        </div>
    </div>

    <div>
        <%--<button id="getShopIdBtn" class="btn btn-success btn-sm" style="left: 250px;top: 450px;position: fixed;">确认</button>--%>
    </div>
</div>

<form action="${contextPath}/ktcount/exportTobaccoExcels" method="post" id="exportExcel" style="display: none">
    <input type="hidden" name="exportExcelshopIds" id="exportExcelshopIds">
    <input type="hidden" name="exportExcelshortshortNames" id="exportExcelshortshortNames">
    <input type="hidden" name="exportExcelshortshopIdNames" id="exportExcelshortshopIdNames">
    <input type="hidden" name="exportExcelYear" id="exportExcelYear">
    <input type="hidden" name="exportExcelWeekNo" id="exportExcelWeekNo">
    <input type="hidden" name="tableType" value="sellwell">
</form>

<script type="text/javascript" src="${contextPath}/static/franchisee/form.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="${contextPath}/static/layer/layer.js"></script>
<script src=${contextPath}/static/layer/layui.all.js></script>
<script>

    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    var myDate = new Date();
    var year = myDate.getFullYear();
    var theWeek = theWeek();
    var laypage = layui.laypage,
        layer = layui.layer,
        laydate = layui.laydate;

    var app = new Vue({
        el: '#app',
        data: {
            year: "提示：当前是"+year+"第"+theWeek+"周",
            queryModel: {},
            shopObj:[],
            shopList: [],
            shopProductList: [],
            productList: [],
            allwkObj: [],
        },
        methods: {

        }
    })

    var shopList;
    var getXYShopTobacco = function () {
        layer.load(1);
        var zoneCode = $("#zoneCode").val();
        var yearId = $("#yearId").val();
        if(yearId == ""){
            yearId = year;
        }
        var dateSearch = $('#dateSearch').val();
        app.year = "提示：当前是"+yearId+"第"+dateSearch+"周数据"

        app.queryModel = {year: yearId, weekNo: dateSearch, zoneCode: zoneCode}
        console.log(app.queryModel);
        $.ajax({
            url: '${contextPath}/ktcount/getXYShopTobacco',
            type: 'post',
            data: app.queryModel,
            success: function (data) {
                layer.closeAll('loading')
                var dataArray = data.data;
                if(dataArray == null || dataArray.length <= 0){
                    layer.msg("提示：没有数据！");
                    return;
                }
                console.log(dataArray)
                var shopObj = [];
                var arrayObj = [];
                shopList = dataArray.shopList;

                var shopProductList = dataArray.shopProductList;
                var productList = dataArray.productList

                for(var i = 0; i < shopList.length + 2; i++){
                    var array = {};
                    if(i == shopList.length){
                        array.shopId = '小计';
                        array.shortName = '小计';
                    }else if(i == shopList.length+1){
                        array.shopId = '需求反馈';
                        array.shortName = '需求反馈';
                    }else {
                        array.shopId = shopList[i].shopId;
                        array.shortName = shopList[i].shortName == null ? shopList[i].shopName : shopList[i].shortName;
                    }
//                console.log(array)
                    shopObj.push(array)
                }
                app.shopList = shopObj;

                var arrayObjs = [];

                for(var i = 0; i < productList.length; i++){
                    var array = [];
                    var confirmQuantityH = 0;
                    for(var r = 0; r < shopList.length + 3; r++){
                        var obj = {}
                        obj.productCode = productList[i].productCode;
                        obj.productName = productList[i].productName;
                        if(r == 0){
                            obj.shopId = "";
                            obj.confirmQuantity = productList[i].productName;
                        }else if (r == shopList.length + 1) {
                            obj.shopId = "";
                            obj.confirmQuantity = confirmQuantityH;
                        } else if (r == shopList.length + 2) {
                            obj.shopId = "";
                            obj.confirmQuantity = productList[i].conclusion;
                        } else {
                            obj.shopId = shopList[r - 1].shopId;
                            obj.shortName = shopList[r - 1].shortName == null ? shopList[r - 1].shopName : shopList[r - 1].shortName;
                            for (var j = 0; j < shopProductList.length; j++) {
                                if (productList[i].productCode == shopProductList[j].productCode && shopList[r - 1].shopId == shopProductList[j].shopId) {
                                    obj.confirmQuantity = shopProductList[j].confirmQuantity;
                                    confirmQuantityH += Number(shopProductList[j].confirmQuantity);
                                    break;
                                } else {
                                    obj.confirmQuantity = 0;
                                }
                            }
                        }
                        array.push(obj);
                    }
//                console.log(array)
                    arrayObjs.push(array)
                }
                app.shopProductList = arrayObjs;
            },
            error: function (error){
                layer.closeAll('loading')
                layer.msg("获取出错："+data.message)
            }
        })
    }

    var saveSingleKtTobaccoOrder = function () {
        layer.load(1);
        var yearId = $("#yearId").val();
        var dateSearch = $("#dateSearch").val();
        var productCode = $("#productCode").val();
        var productName = $("#productName").val();
        var shopId = $("#shopId").val();
        var confirmQuantity = $("#confirmQuantity").val();

        app.queryModel = {type: 2, year: yearId, weekNo: dateSearch,productCode: productCode,productName: productName, shopId: shopId, confirmQuantity: confirmQuantity, conclusion: confirmQuantity}
        console.log(app.queryModel)
        if (!shopId){
            saveShopTobaccoRequirement();
            return
        }
        $.ajax({
            url: '${contextPath}/ktcount/saveSingleKtTobaccoOrder',
            type: 'post',
            data: app.queryModel,
            success: function (data) {
                layer.closeAll('loading')
                layer.close(modalIndex);
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                layer.msg("提示："+data.message)
                getXYShopTobacco();
            },
            error: function (error){
                layer.close(modalIndex);
                layer.closeAll('loading')
                layer.msg("获取出错："+data.message)
            }
        })
    }

    var saveShopTobaccoRequirement = function () {
        layer.load(1);
        $.ajax({
            url: '${contextPath}/ktcount/saveShopTobaccoRequirement',
            type: 'post',
            data: app.queryModel,
            success: function (data) {
                layer.closeAll('loading')
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                layer.msg("提示："+data.message)
                getXYShopTobacco();

            },
            error: function (error){
                layer.closeAll('loading')
                layer.msg("获取出错："+data.message)
            }
        })
    }

    var singleKtTobaccoOrder = function (productCode,shopId,confirmQuantity,productName) {
        layer.load(1);
        console.log(productName)
        var yearId = $("#yearId").val();
        var dateSearch = $("#dateSearch").val();
        if(dateSearch == ""){
            layer.closeAll('loading')
            layer.msg("提示：请选择年周！")
            return;
        }
        $("#productCode").val(productCode);
        $("#productName").val(productName);
        $("#shopId").val(shopId);
        $("#confirmQuantity").val(confirmQuantity);
        var title = '请输入要货数量'
        if (!shopId){
            title = '需求反馈'
        }
        $("#authorizationInfoContent").removeClass("hide")
        modalIndex = layer.open({
            type: 1,
            title: title,
            closeBtn: 1,
            shadeClose: true,
            maxmin: true,
            area: ['260px', '110px'],
            skin: 'yourclass',
            content: $("#authorizationInfoContent"),
            end: function () {
                $("#authorizationInfoContent").addClass("hide")
            }
        });
        layer.closeAll('loading')
    }

    var allwk = getNumOfWeeks();
    console.log(allwk)
    for(var i = 1; i < allwk + 1; i++){
        var array = {};
        array.allwk = i;
        if(i == theWeek){
            array.selected = 'selected';
            var showDate = getDateRange(year,i);
            document.getElementById("_dateRange_import").value=showDate;
        }
        app.allwkObj.push(array);
    }

    var tablesToExcel = function () {
        var yearId = $("#yearId").val();
        var dateSearch = $('#dateSearch').val();
        var shortName = '';
        var shopId = '';

        var shopList = app.shopList;

        console.log(shopList);
        var shopIds = '';
        var shortNames = '';
        var shopIdNames = '';
        for(var i = 0; i < shopList.length; i++){
            var shortName = shopList[i].shortName == null ? shopList[i].shopName : shopList[i].shortName;
//            console.log(shortName);
            if(shopIds == ''){
                shopIds = "'"+shopList[i].shopId;
                shortNames = shortName;
                shopIdNames = "'"+shopList[i].shopId+"' "+shortName;
            }else {
                if(i < shopList.length - 2) {
                    shopIds = shopIds + "','" + shopList[i].shopId
                    shopIdNames = shopIdNames + ", '" + shopList[i].shopId + "' " + shortName;
                }
                shortNames = shortNames + ', ' + shortName;
            }
        }


        $("#exportExcelshopIds").val(shopIds+"'".replace("//s/g", ""))
        $("#exportExcelshortshortNames").val(shortNames.replace("//s/g", ""))
        $("#exportExcelshortshopIdNames").val(shopIdNames.replace("//s/g", ""))
        $("#exportExcelYear").val(yearId)
        $("#exportExcelWeekNo").val(dateSearch)
        $("#exportExcel").submit();
    }

    //获取区域
    var getZone = function(){
        layer.load(1);
        var filters = {
            "rules": [
                // {"field": "parentId", "data": '0'},
                {"field": "state", "data": '1'},
            ]
        };
        var queryModels = {
            page: '1',
            rows: '10000',
            filters: JSON.stringify(filters),
        };

        console.log(queryModels)

        $.ajax({
            url : "${contextPath}/ktCommon/getZoneListByPage",
            type : "get",
            data : queryModels,
            dataType : "json",
            async : false,
            success : function(data) {
                layer.closeAll('loading');
                var dataArray = data.recordList;
                zoneArray = dataArray;
            },
            error : function () {
                layer.closeAll('loading');
                layer.msg("网络异常")
            }
        });
    }

    var zoneHs = function () {
        $("#zoneName").val('');
        $("#zoneCode").val('');

        var setting = {
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: '',
                },
                key: {
                    name: 'zoneName'
                }
            },
            <%--async: {--%>
            <%--enable: false, // 设置 zTree是否开启异步加载模式  加载全部信息--%>
            <%--url: "${contextPath}/ktProd/getProdType", // Ajax 获取数据的 URL 地址--%>
            <%--autoParam: ["0"],    // 异步加载时自动提交父节点属性的参数,假设父节点 node = {id:1, name:"test"}，异步加载时，提交参数 zId=1--%>
            <%--//                dataFilter: queryModels,--%>
            <%--},--%>
            callback: { //回调函数
                /**
                 * event:鼠标事件
                 * treeId：树的容器id
                 * treeNode：当前点击的节点
                 */
                //双击
                onDblClick: function (treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("zoneDemo");
                    var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
                    console.log(node[0].zoneName)
                    $("#zoneName").val(node[0].zoneName);
                    $("#zoneCode").val(node[0].zoneCode);
                    layer.close(modalIndexZone)
                }
            }
        }
        console.log(zoneArray)

        var zNodes =[];
        $.fn.zTree.init($("#zoneDemo"), setting, zoneArray);
        $("#authorizationInfoContentZone").removeClass("hide")
        modalIndexZone = layer.open({
            type: 1,
            title: '区域',
            closeBtn: 1,
            shadeClose: true,
            maxmin: true,
            area: ['300px','500px'],
            skin: 'yourclass',
            content: $("#authorizationInfoContentZone"),
            end: function () {
                $("#authorizationInfoContentZone").addClass("hide")
            }
        });
    }

    $(function () {
        getZone();
        getXYShopTobacco();
    })



</script>

<!-- 时间控件 -->
<script type="text/javascript">
    $('#turnCreateDate').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',  //汉化
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
//        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
        autoclose:true, //选择日期后自动关闭
        minuteStep:1,
//        startDate:new Date(),
    });

    $('#bindCreateDate').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',  //汉化
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        forceParse: 0,
        showMeridian: 1,
        format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
        autoclose:true, //选择日期后自动关闭
        minuteStep:1,
//        startDate:new Date(),
    });
</script>

</body>
</html>
